package nio.example.study.client;

import com.google.common.util.concurrent.Uninterruptibles;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import nio.example.study.client.codec.*;
import nio.example.study.client.codec.dispatcher.ClientIdleCheckHandler;
import nio.example.study.client.codec.dispatcher.KeepaliveHandler;
import nio.example.study.common.RequestMessage;
import nio.example.study.common.auth.AuthOperation;
import nio.example.study.common.order.OrderOperation;
import nio.example.study.util.IdUtil;


import javax.net.ssl.SSLException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class Client {

	public static void main(String[] args) throws ExecutionException, InterruptedException, SSLException {
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.group(new NioEventLoopGroup());

		KeepaliveHandler keepaliveHandler = new KeepaliveHandler();

		//SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
		//SslContext sslContext = sslContextBuilder.build();

		bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
			@Override
			protected void initChannel(NioSocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();

				pipeline.addLast(new ClientIdleCheckHandler());

				//pipeline.addLast(sslContext.newHandler(ch.alloc()));

				pipeline.addLast(new OrderFrameDecoder());
				pipeline.addLast(new OrderFrameEncoder());
				pipeline.addLast(new OrderProtocolEncoder());
				pipeline.addLast(new OrderProtocolDecoder());

				pipeline.addLast(keepaliveHandler);

				pipeline.addLast(new OperationToRequestMessageEncoder());
				pipeline.addLast(new LoggingHandler(LogLevel.INFO));
			}
		});
		ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8090);
		channelFuture.sync();

		OrderOperation orderOperation = new OrderOperation(1001, "tudou");

		AuthOperation authOperation = new AuthOperation("admin", "password");
		//RequestMessage requestMessage = new RequestMessage(IdUtil.nextId(), authOperation);
		channelFuture.channel().writeAndFlush(authOperation);

		channelFuture.channel().writeAndFlush(orderOperation);


		channelFuture.channel().closeFuture().get();
	}
}
